package com.lagou.client;

import com.lagou.service.RpcRequest;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.*;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class RpcConsumer {

    //创建线程池对象
    private static final ExecutorService executor = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors());

    private List<String> hosts = new ArrayList<>();

    private Map<String, Invoke> invokeMap = new HashMap<>();

    private int index = 0;

    //1.创建一个代理对象 providerName：UserService#sayHello are you ok?
    public Object createProxy(final Class<?> serviceClass) {
        //借助JDK动态代理生成代理对象
        return Proxy.newProxyInstance(Thread.currentThread().getContextClassLoader(), new Class<?>[]{serviceClass}, new InvocationHandler() {
            public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                //（1）调用初始化netty客户端的方法
                //封装
                RpcRequest request = new RpcRequest();
                String requestId = UUID.randomUUID().toString();
                System.out.println(requestId);

                String className = method.getDeclaringClass().getName();
                String methodName = method.getName();

                Class<?>[] parameterTypes = method.getParameterTypes();

                request.setRequestId(requestId);
                request.setClassName(className);
                request.setMethodName(methodName);
                request.setParameterTypes(parameterTypes);
                request.setParameters(args);

                if (!hosts.isEmpty()){
                    String host = getHost();
                    System.out.println("当前host:" + host);
                    Invoke invoke = invokeMap.get(host);
                    // 设置参数
                    invoke.getUserClientHandler().setPara(request);
                    System.out.println(request);
                    System.out.println("设置参数完成");

                    // 去服务端请求数据

                    return executor.submit(invoke.getUserClientHandler()).get();
                }
                return null;
            }
        });
    }

    private synchronized String getHost(){
        String host = this.hosts.get(index);
        if (index < hosts.size() - 1){
            index ++;
        } else {
            index = 0;
        }
        return host;
    }

    //2.初始化netty客户端
    public synchronized void initClient(List<String> hosts) throws Exception {
        this.hosts = new ArrayList<>();
        this.hosts.addAll(hosts);
        for (String host : hosts) {
            Invoke invoke = new Invoke();
            invoke.initClient(host);
            invokeMap.put(host, invoke);
        }
    }

    //2.初始化netty客户端
    public synchronized void initClient(String host) throws Exception {
        if (!invokeMap.containsKey(host)){
            this.hosts.add(host);
            Invoke invoke = new Invoke();
            invoke.initClient(host);
            invokeMap.put(host,invoke);
        }
    }

    public synchronized void close(String host) throws InterruptedException {
        this.hosts.remove(host);
        Invoke invoke = invokeMap.get(host);
        invoke.close();
        invokeMap.remove(host);
    }

}